package com.xiamaliu.spring.webmvc.servlet;

import com.xiamaliu.spring.annotation.GPController;
import com.xiamaliu.spring.annotation.GPRequestMapping;
import com.xiamaliu.spring.context.GPApplicationContext;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@NoArgsConstructor
public class GPDispatcherServlet extends HttpServlet {

    private final String CONTEXT_CONFIG_LOCATION = "contextConfigLocation";

    private GPApplicationContext context;

    private List<GPHandlerMapping> handlerMappings = new ArrayList<GPHandlerMapping>();

    private Map<GPHandlerMapping, GPHandlerAdapter> handlerAdapters = new HashMap<GPHandlerMapping, GPHandlerAdapter>();

    private List<GPViewResolver> viewResolvers = new ArrayList<GPViewResolver>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            this.doDispatch(req, resp);
        } catch (Exception e) {
            resp.getWriter().write("500 Exception,Details:\r\n" + Arrays.toString(e.getStackTrace()).replaceAll("\\[|\\]", "").replaceAll(",\\s", "\r\n"));
            e.printStackTrace();
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 1、通过从request中拿到URL，去匹配一个HandlerMapping
        GPHandlerMapping handler = this.getHandler(req);
        if (handler == null) {
            processDispatchResult(req, resp, new GPModelAndView("404"));
            return;
        }

        // 2、准备调用前的参数
        GPHandlerAdapter ha = getHandlerAdapter(handler);

        // 3、真正的调用方法，返回ModelAndView存储了要穿页面上的值，和页面模板的名称
        GPModelAndView mv = ha.handler(req, resp, handler);

        // 4、这一步才是真正的输出
        processDispatchResult(req, resp, mv);
    }

    private void processDispatchResult(HttpServletRequest req, HttpServletResponse resp, GPModelAndView mv) throws IOException {
        // 把给我的ModelAndView变成一个HTML、OutputStream、json、freemark、veolcity
        if (mv == null) {
            return;
        }

        // 如果ModelAndView不为null，该怎么办
        if (this.viewResolvers.isEmpty()) {
            return;
        }

        for (GPViewResolver viewResolver : this.viewResolvers) {
            GPView view = viewResolver.resolveViewName(mv.getViewName(), null);
            view.render(mv.getModel(), req, resp);
            return;
        }
    }

    private GPHandlerAdapter getHandlerAdapter(GPHandlerMapping handler) {
        if (this.handlerAdapters.isEmpty()) {
            return null;
        }
        GPHandlerAdapter ha = this.handlerAdapters.get(handler);
        if (ha.supports(handler)) {
            return ha;
        }
        return null;
    }

    private GPHandlerMapping getHandler(HttpServletRequest req) throws Exception {
        if (this.handlerMappings.isEmpty()) {
            return null;
        }

        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+", "/");

        for (GPHandlerMapping handler : this.handlerMappings) {
            try {
                Matcher matcher = handler.getPattern().matcher(url);
                if (!matcher.matches()) {
                    continue;
                }
                return handler;
            } catch (Exception e) {
                throw e;
            }
        }
        return null;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1、初始化ApplicationContext
        context = new GPApplicationContext(config.getInitParameter(CONTEXT_CONFIG_LOCATION));
        // 2、初始化Spring MVC九大组件
        initStrategies(context);
    }

    // 初始化策略
    private void initStrategies(GPApplicationContext context) {
        // handlerMapping，必须实现
        initHandlerMappings(context);
        // 初始化参数适配器，必须实现
        initHandlerAdapters(context);
        // 初始化视图转换器，必须实现
        initViewResolvers(context);
    }

    private void initViewResolvers(GPApplicationContext context) {

        // 拿到模板的存放目录
        String templateRoot = context.getConfig().getProperty("templateRoot");
        String templateRootPath = this.getClass().getClassLoader().getResource(templateRoot).getFile();

        File templateRootDir = new File(templateRootPath);
        String[] templates = templateRootDir.list();

        for (int i = 0; i < templates.length; i++) {
            // 这里主要是为了兼容多模板，所有模仿Spring用List保存
            // 在我写的代码中简化了，其实只有需要一个模板就可以搞定
            // 只是为了仿真，所有还是搞了一个List
            this.viewResolvers.add(new GPViewResolver(templateRoot));
        }
    }

    private void initHandlerAdapters(GPApplicationContext context) {
        // 把一个request请求变成一个handler，参数都是字符串的，自动配到handler中的形参

        // 可想而知，他要拿到HandlerMapping才能干活
        // 就意味着，有几个HandlerMapping就有几个HandlerAdapter
        for (GPHandlerMapping handlerMapping : this.handlerMappings) {
            this.handlerAdapters.put(handlerMapping, new GPHandlerAdapter());
        }
    }

    private void initHandlerMappings(GPApplicationContext context) {
        String[] beanNames = context.getBeanDefinitionNames();
        try {
            for (String beanName : beanNames) {

                Object controller = context.getBean(beanName);

                Class<?> clazz = controller.getClass();

                if (!clazz.isAnnotationPresent(GPController.class)) {
                    continue;
                }

                String baseUrl = "";
                // 获取controller的url配置
                if (clazz.isAnnotationPresent(GPRequestMapping.class)) {
                    GPRequestMapping requestMapping = clazz.getAnnotation(GPRequestMapping.class);
                    baseUrl = requestMapping.value();
                }

                // 获取 Method 的url配置
                Method[] methods = clazz.getMethods();
                for (Method method : methods) {
                    // 没有加RequestMapping注解直接忽略
                    if (!method.isAnnotationPresent(GPRequestMapping.class)) {
                        continue;
                    }

                    // 映射 URL
                    GPRequestMapping requestMapping = method.getAnnotation(GPRequestMapping.class);

                    String regex = ("/" + baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/").replaceAll("\\*", ".*");

                    Pattern pattern = Pattern.compile(regex);

                    this.handlerMappings.add(new GPHandlerMapping(controller, method, pattern));
                    log.info("Mapped {},{}", regex, method);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
